package com.polaris.live.im.manager

import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.util.StructUtils
import com.polaris.live.im.db.database.AppDatabase
import com.polaris.live.im.db.entity.GreetMessageEntity
import com.polaris.live.im.db.entity.MessageEntity

/**
 * 打招呼消息管理
 *
 * @author Created by 半仙 on 2024/4/26/026 21:23
 */
object ImGreetMessageManager {

    //用户id
    private val mUserList = StructUtils.newSaleSet<String>()

    suspend fun insertMessage(messageEntity: MessageEntity) {
        AppDatabase.instance.greetMessageEntityDao().apply {
            val greetMessageEntity = messageEntity.toGreetMessageEntity()

            val id = "${messageEntity.otherId}:${UserManager.getUserId()}"
            if (!mUserList.add(id)) {
                return
            }
            //只需要查我与他是否存在消息就行     因为只有flagGreetPushMessage = 1才会存到这个表里
            val haveMessage =
                findMessageByUserIdAndMsgId(UserManager.getUserId(), messageEntity.otherId)
            if (haveMessage == null) {
                saveMessage(greetMessageEntity)
            }
        }
    }
}

fun MessageEntity.toGreetMessageEntity(): GreetMessageEntity {
    return GreetMessageEntity(
        tableId = "${this.otherId}:${UserManager.getUserId()}",
        userId = UserManager.getUserId(),
        otherId = this.otherId,
        pushDetailId = this.payloadBean?.pushDetailId
    )
}